package com.dly.hope.controller;

import com.dly.hope.annotation.LoginRole;
import com.dly.hope.constant.R;
import com.dly.hope.ro.FileRo;
import com.dly.hope.type.PermissionsType;
import com.dly.hope.vo.FileVo;
import com.dly.hope.servce.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @author linyu.dai
 * @project myserve
 * @description 文件controller
 * @creat 2022/8/30 15:29:45
 */
@RestController
@Api(tags = "文件相关接口")
@RequestMapping(value = "/file")
public class FileController extends BaseController{

    @Resource
    private FileService fileService;

    //一定要告诉swagger未文件类型提交
    @ApiOperation(value = "上传文件",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    //设置上传类型未表单提交
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @LoginRole
    public ResponseEntity<R<FileVo>> upload(@Valid FileRo fileRo, BindingResult br){
        return operate(()->this.successDate(fileService.save(fileRo)),br);
    }

    @ApiOperation(value = "加载文件")
    @GetMapping(value = "/load")
    public ResponseEntity<R<Void>> load(HttpServletResponse response, String token){
        fileService.load(response, token);
        return operate(this::success);
    }

    @ApiOperation(value = "加载文件(带文件id的)")
    @GetMapping(value = "/loadFileId")
    public ResponseEntity<R<Void>> fileIdLoad(HttpServletResponse response, String fileId){
        fileService.fileIdLoad(response, fileId);
        return operate(this::success);
    }

    @ApiOperation(value = "通过文件id获取带token的url")
    @GetMapping(value = "/getTokenLoad")
    @LoginRole(permissions = {PermissionsType.UPLOAD_FILE})
    public ResponseEntity<R<String>> load(String fileId){
        return operate(()->this.successDate(fileService.getLoad(fileId)));
    }

    @ApiOperation(value = "通过文件id删除文件")
    @PostMapping("/delete/{fileId}")
    @LoginRole(permissions = {PermissionsType.DELETE_FILE})
    private ResponseEntity<R<Void>> remove(@PathVariable(value = "fileId") String fileId){
        fileService.delete(fileId);
        return operate(this::success);
    }
}
